package hu.myai.util;

import hu.myai.model.db.AxHistory;
import hu.myai.model.misc.KeyValue;

import java.util.ArrayList;
import java.util.List;

import org.joone.log.ILogger;
import org.joone.log.LoggerFactory;

/**
 * @author bozbalint This is represent the analyst
 */
public class Analyst extends Thread {

	private static final ILogger log = LoggerFactory.getLogger(Analyst.class);

	private DatabaseUtil dbUtil = new DatabaseUtil();

	private Scenario scenario = new Scenario();

	private Thread myThread;

	private List<Thread> myThreads = new ArrayList<Thread>();

	private String symbol;

	private int mode;

	/** Whether the analyst is running */
	protected transient boolean running = false;

	public static List<String> goodForTrade = new ArrayList<String>();

	// This method is called when the thread runs
	public void run() {
		running = true;
		preEvaluation(symbol, mode);
	}

	public synchronized Thread start(String symbol, int mode) {
		Analyst analyst = new Analyst();
		analyst.symbol = symbol;
		analyst.mode = mode;

		analyst.myThread = new Thread(analyst);
		analyst.myThread.start();

		myThreads.add(analyst.myThread);
		return analyst.myThread;
	}

	/**
	 * Waits for the current analyst thread to stop
	 */
	public void finish() {
		try {
			for (Thread thread : myThreads) {
				if (thread != null)
					thread.join();
			}
		} catch (InterruptedException doNothing) {
		}
	}

	public Boolean preEvaluation(String stock, int mode) {

		// database.entityManager = entityManager;

		List<AxHistory> observedStock = dbUtil.getSavedHistoryList(null, stock, 100);

		if (observedStock.size() < 20) {
			log.error("Error - Not enough data");
			return false;
		}

		Charting charting = new Charting(stock);

		List<KeyValue[]> resultList = new ArrayList<KeyValue[]>();

		Trend trend = charting.getPivoSequence(observedStock);
		log.debug("Scale is logaritmic: " + Constans.logarithmic);
		trend.trendInit(mode);

		List<Double> williamsR = trend.getWilliamsR().getWilliamsRList();
		List<Double> rateOfChange = trend.getRateOfChange().getRocList();

		// not interested in if
		if (!scenario.risingIndicator(williamsR, rateOfChange))
			return false;

		// there is volume
		if (!scenario.tradeIsOngoing(trend.getStockList()))
			return false;

		log.debug(trend.toString());
		goodForTrade.add(stock);
		resultList.add(trend.getNext());

		// analyst
		Constans.logarithmic = !Constans.logarithmic;
		log.debug("Scale is logaritmic: " + Constans.logarithmic);
		trend.trendInit(mode);
		log.debug(trend.toString());
		resultList.add(trend.getNext());

		Util util = new Util();
		KeyValue[] retValue = util.closestSupports(resultList);
		System.out.println("symbol: " + stock + " \t " + retValue[0] + " - " + retValue[1]);

		return true;
		// analyst
	}
}
